package publisher

import (
	"encoding/json"
	"github.com/streadway/amqp"
	cfg "github.com/ufoscout/go-up"
	"go.uber.org/zap"
	_const "longmen/server/pkg/common/helper/const"
	"longmen/server/pkg/common/lib/rabbitmq"
)

type (
	BroadCastType    string
	BroadCastMessage struct {
		TypeName _const.BroadCastType
		Msg      []byte
	}
	PublishTxChatServices struct {
		instance *rabbitmq.Producer // 发送实例
	}
)

const (
	GiftHeat        = _const.GiftHeat        // 礼物热度更新
	ClearChat       = _const.ClearChat       // 清理腾讯聊天室历史记录
	Login           = _const.Login           // 登录广播
	AnonymousLogin  = _const.AnonymousLogin  // 匿名登录广播
	SubscribeAnchor = _const.SubscribeAnchor // 关注直播间
	ChangeProps     = _const.ChangeProps     // 更新挂件
	AdminLog        = _const.AdminLog        // 管理员操作日志
	HistoryToEs     = _const.HistoryToEs     // 历史记录写入Es
	AllMemberPush   = _const.AllMemberPush   // 群推送
	AutoChat        = _const.AutoChat        // 自动发言
)

// NewTxChatPublish 开启一个生产实例
func NewTxChatPublish(conf cfg.GoUp, rabbitConf rabbitmq.Config, publishName string, logger *zap.SugaredLogger) (*PublishTxChatServices, error) {
	mq := rabbitmq.New(&rabbitConf, logger)
	c, queue, options := rabbitmq.GetRabbitProducerConfig(conf, publishName)
	producer, err := mq.NewProducer(c, queue, options)
	if err != nil {
		logger.Errorf("new producer err: %v", err)
		return nil, err
	}

	return &PublishTxChatServices{
		instance: producer,
	}, nil
}

// BroadCast 广播消息
func (p *PublishTxChatServices) BroadCast(typeName _const.BroadCastType, msg interface{}) error {
	body, err := json.Marshal(msg)
	if err != nil {
		return err
	}
	sendBody, _ := json.Marshal(BroadCastMessage{
		TypeName: typeName,
		Msg:      body,
	})
	return p.instance.Publish(amqp.Publishing{
		DeliveryMode: amqp.Persistent,
		ContentType:  "application/json",
		Body:         sendBody,
	})
}
